import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useDeviceStore } from '../stores/deviceStore'

const LoginPage: React.FC = () => {
  const [tab, setTab] = useState<'phone' | 'password'>('phone')
  const [phone, setPhone] = useState('')
  const [smsCode, setSmsCode] = useState('')
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [smsSent, setSmsSent] = useState(false)
  const [smsCountdown, setSmsCountdown] = useState(0)
  const navigate = useNavigate()
  const setUser = useDeviceStore(state => state.setUser)
  const fetchDevices = useDeviceStore(state => state.fetchDevices)

  // 模拟登录逻辑
  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setError(null)
    try {
      let user = null
      if (tab === 'phone') {
        if (!/^1\d{10}$/.test(phone)) throw new Error('请输入有效手机号')
        if (!smsCode) throw new Error('请输入验证码')
        // 调用后端API进行手机号+验证码登录
        const res = await fetch('/api/login/sms', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ phone, code: smsCode })
        })
        if (!res.ok) throw new Error('登录失败')
        user = await res.json()
      } else {
        if (!username) throw new Error('请输入用户名')
        if (!password) throw new Error('请输入密码')
        // 调用后端API进行用户名密码登录
        const res = await fetch('/api/login/password', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ username, password })
        })
        if (!res.ok) throw new Error('登录失败')
        user = await res.json()
      }
      // 登录成功，保存用户信息
      setUser(user)
      localStorage.setItem('token', user.token)
      await fetchDevices()
      navigate('/')
    } catch (err: any) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }

  // 模拟发送验证码
  const handleSendSms = async () => {
    if (!/^1\d{10}$/.test(phone)) {
      setError('请输入有效手机号')
      return
    }
    setError(null)
    setSmsSent(true)
    setSmsCountdown(60)
    // 调用后端API发送验证码
    try {
      const res = await fetch('/api/send-sms', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone })
      })
      if (!res.ok) throw new Error('验证码发送失败')
    } catch (err: any) {
      setError(err.message)
    }
    const timer = setInterval(() => {
      setSmsCountdown(prev => {
        if (prev <= 1) {
          clearInterval(timer)
          setSmsSent(false)
          return 0
        }
        return prev - 1
      })
    }, 1000)
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50">
      <div className="w-full max-w-md bg-white rounded-lg shadow p-6">
        <h2 className="text-2xl font-bold text-center mb-6">用户登录</h2>
        <div className="flex mb-4">
          <button
            className={`flex-1 py-2 rounded-l ${tab === 'phone' ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-700'}`}
            onClick={() => setTab('phone')}
          >
            手机号登录
          </button>
          <button
            className={`flex-1 py-2 rounded-r ${tab === 'password' ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-700'}`}
            onClick={() => setTab('password')}
          >
            用户名密码
          </button>
        </div>
        <form onSubmit={handleLogin} className="space-y-4">
          {tab === 'phone' ? (
            <>
              <input
                type="text"
                placeholder="手机号"
                className="input w-full"
                value={phone}
                onChange={e => setPhone(e.target.value)}
                disabled={loading}
              />
              <div className="flex space-x-2">
                <input
                  type="text"
                  placeholder="验证码"
                  className="input flex-1"
                  value={smsCode}
                  onChange={e => setSmsCode(e.target.value)}
                  disabled={loading}
                />
                <button
                  type="button"
                  className="btn btn-secondary"
                  onClick={handleSendSms}
                  disabled={smsSent || loading}
                >
                  {smsSent ? `${smsCountdown}s后重发` : '发送验证码'}
                </button>
              </div>
            </>
          ) : (
            <>
              <input
                type="text"
                placeholder="用户名"
                className="input w-full"
                value={username}
                onChange={e => setUsername(e.target.value)}
                disabled={loading}
              />
              <input
                type="password"
                placeholder="密码"
                className="input w-full"
                value={password}
                onChange={e => setPassword(e.target.value)}
                disabled={loading}
              />
            </>
          )}
          {error && <div className="text-red-500 text-sm text-center">{error}</div>}
          <button
            type="submit"
            className="btn btn-primary w-full"
            disabled={loading}
          >
            {loading ? '登录中...' : '登录'}
          </button>
        </form>
      </div>
    </div>
  )
}

export default LoginPage 